//
//  NetworkTool.swift
//  MMTest
//
//  Created by liujianlong on 2022/9/28.
//

import UIKit
import Moya
import SwiftyJSON
class NetworkTool: NSObject {
    
    class func request(_ api:EPApi , _ backALL:Bool=false , _ callback:((_ response: JSON)->Void)?,_ progressBlock:((_ total:Int,_ complete:Int)->Void)?=nil)
    {
        ///api = EPApi.history
        let order = MoyaProvider<EPApi>()
        
        ///下载进度
        let progressClosure: Moya.ProgressBlock = { progress in
            // 进度更新处理
            progressBlock?(Int(progress.progressObject?.totalUnitCount ?? 0), Int(progress.progressObject?.completedUnitCount ?? 0))
            print("下载进度: \(progress.progress * 100)")
            if progress.response?.response?.statusCode == 200 {
                let dict = ["fileURL":api.localLocation.absoluteString]
                callback?(JSON(dict))
            }
        }
        
        ///
        order.request(api,progress: progressClosure) { result in
            switch result {
            case let .success(result):
                let data = result.data
                guard let jsonData = try? JSON(data: data) else{return}
                let code = jsonData["code"].intValue
                if code == 200 || backALL == true {
                    callback?(jsonData)
                }else{
//                    XSTipsHUD.hideAllTips()
//                    XSTipsHUD.showText("code:\(jsonData["code"])"+"\n"+jsonData["msg"].stringValue)
                }
            case let .failure(result):
                switch result{
                case .underlying:
                    callback?(["code":NSNumber(value: 10000),"msg":"请检查网络状态"])
                default:
                    break
                }
                break
            }
            print("result = \(result)")
        }
    }
    
}
